package com.zlz.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * @author zhulinzhong
 * @date 2022-01-25 11:02:38
 */
public class LogFormatter extends Formatter {
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    private static final DecimalFormat THREE_PATTERN = new DecimalFormat("000");
    private static final DecimalFormat TWO_PATTERN = new DecimalFormat("00");

    @Override
    public synchronized String format(LogRecord record) {
        StringBuilder sb = appendEmpty(record);
        if (record.getThrown() != null) {
            try {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                record.getThrown().printStackTrace(pw);
                pw.close();
                sb.append(sw);
            } catch (Exception ex) {
            }
        }
        sb.append(LINE_SEPARATOR);
        return sb.toString();
    }

    /**
     * 拼接日志信息
     *
     * @param record
     */
    private StringBuilder appendInfo(LogRecord record) {
        StringBuilder sb = new StringBuilder();

        Calendar cal = Calendar.getInstance();
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minutes = cal.get(Calendar.MINUTE);
        int seconds = cal.get(Calendar.SECOND);
        int millis = cal.get(Calendar.MILLISECOND);
        sb.append(TWO_PATTERN.format(hour)).append(':');
        sb.append(TWO_PATTERN.format(minutes)).append(':');
        sb.append(TWO_PATTERN.format(seconds)).append('.');
        sb.append(THREE_PATTERN.format(millis)).append(' ');

        sb.append(record.getLevel().getLocalizedName());
        sb.append(": ");

        // caller method
        sb.append(record.getSourceClassName());
        sb.append(' ');
        sb.append(record.getSourceMethodName());
        sb.append(' ');

        return sb;
    }

    /**
     * 仅拼接用户输入信息
     *
     * @param record
     * @return
     */
    private StringBuilder appendEmpty(LogRecord record) {
        StringBuilder sb = new StringBuilder();
        sb.append(record.getMessage());
        return sb;
    }
}
